package com.traffic.between.service;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;


public class LingDianServiceImpl {
	private static Logger logger = Logger.getLogger(LingDianServiceImpl.class);
	public static LingDianServiceImpl service = new LingDianServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.LINGDIAN_ORDER_URL;
	private static String LINGDIAN_APPKEY = BetweenProperties.LINGDIAN_APPKEY;
	private static String LINGDIAN_USERNAME = BetweenProperties.LINGDIAN_USERNAME;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.LINGDIAN_ORDERSTATUS_URL;
	
	

	public String order(String spec, String mobiles, String tradeNo, String url,String region) {
		
        String username = LINGDIAN_USERNAME;
        String key = LINGDIAN_APPKEY;
        String effectiveType = "tm";//本月生效
        String areaType = "0".equals(region)? "c":"p";// 0-国内 1-省内
        
        long timestamp = System.currentTimeMillis();
       
        String waitSig = timestamp + tradeNo + mobiles + spec + url + key;
        
        String signature = getMD5(waitSig.trim());
        
        String result = "";
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("username", username);
        params.put("signature", signature);
        params.put("tradeNo", tradeNo);
        params.put("mobiles", mobiles);
        params.put("spec", spec);
        params.put("areaType", areaType);
        params.put("effectiveType", effectiveType);
        params.put("timestamp", timestamp);
        params.put("url",url);
	    
        String jsonStr = new Gson().toJson(params);
		HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		logger.info("between- 零点流量订购请求时的参数: "+jsonStr);
		try {
			StringEntity body = new StringEntity(jsonStr, "utf-8");
			body.setContentEncoding("utf-8");
			body.setContentType("application/json");
			httpPost.setEntity(body);
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 零点流量订购请求时的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
				logger.info("between- 零点流量订购请求时的响应数据是: " + result);
			}
		} catch (Exception e) {
			logger.info("between- 零点流量订购请求时异常: " + e);
		}

	
		return result;
	}

	

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5STR " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}

	public static void main(String[] args) {
		
		String json = "{\"code\": \"0000\", \"msg\": \"成功\", \"data\": [{\"customerId\": \"0fdb45131237498abea2d81d848ae6fd\", \"customerName\": \"荣米科技\",\"amount\": \"10204.00\" }]}";
		JSONObject jsonObject = JSONObject.fromObject(json);
		System.out.println(jsonObject.get("data"));
		
 
	}

}
